import sys
import os
import json
import aria2p
host = os.getenv('ARIA2_HOST')
port = os.getenv('ARIA2_PORT')
secret = os.getenv('ARIA2_SECRET')
aria2 = aria2p.API(
    aria2p.Client(
        host=host,
        port=port,
        secret=secret
    )
)
downloads = aria2.get_downloads()
aria2_downloadslist = {}
for download in downloads:
    if download.is_torrent:
        aria2_downloadslist[download.gid] = download

def put_gid(torrent_path, gid):
    gid_path = torrent_path + '.gid'
    with open(gid_path, 'w') as f:
        gid = f.write(gid)

not_downloaded = json.loads(sys.argv[1])
for path in not_downloaded:
    obj = not_downloaded[path]
    name = obj['name']
    if 'gid' not in obj or obj['gid'] not in aria2_downloadslist:
        try:
            download = aria2.add_torrent(path) # 如果下载列表里没有就add_torrent
            put_gid(path, download.gid) # 并记下gid
        except Exception as e:
            pass
    else:
        gid = obj['gid']
        download = aria2_downloadslist[gid]
        if download.is_complete: # 如果下载列表里显示下载完成
            for path in download.root_files_paths:
                print('download.sh "%s"' % path) # 就将文件下载到本地
                print('remove.sh "%s"' % path) # 然后删除
            download.remove() # 并删除任务
        elif download.is_active or download.is_waiting or download.is_paused: # 如果下载列表里显示正在下载或者在等待
            pass # 什么都不做
        else:
            download.remove() # 其他情况直接删除任务
            for path in download.root_files_paths:
                print('remove.sh "%s"' % path) # 并删除文件
